package com.yourenbang.lingyun.transaction.web.service.impl.migrate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.parser.ParserConfig;
import com.yourenbang.lingyun.constants.enums.ChannelIdEnums;
import com.yourenbang.lingyun.constants.enums.FundBillType;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.constants.enums.fund.AccountType;
import com.yourenbang.lingyun.constants.enums.fund.ScoreAccountType;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.StringUtils;
import com.yourenbang.lingyun.core.util.date.DateFormat;
import com.yourenbang.lingyun.core.util.date.LocalDateUtils;
import com.yourenbang.lingyun.core.util.redis.RedisUtils;
import com.yourenbang.lingyun.domain.ScoreBill;
import com.yourenbang.lingyun.mapper.FundAccountMapper;
import com.yourenbang.lingyun.mapper.ScoreAccountMapper;
import com.yourenbang.lingyun.mapper.ScoreBillMapper;
import com.yourenbang.lingyun.mapper.UserBaseExtMapper;
import com.yourenbang.lingyun.transaction.config.AcmTransactionParams;
import com.yourenbang.lingyun.transaction.mapper.TransactionFundBillMapper;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.FundBillDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.QueryTableDateDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.QueryTablePageDTO;
import com.yourenbang.lingyun.transaction.web.domain.po.FundBill;
import com.yourenbang.lingyun.transaction.web.service.migrate.CommonMigrateService;
import com.yourenbang.lingyun.transaction.web.service.migrate.FundBillMigrateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class FundBillMigrateServiceImpl extends AbstractMigrateService implements FundBillMigrateService {

    @Autowired
    private RedisUtils redis;
    @Autowired
    private CommonMigrateService commonMigrateService;
    @Autowired
    private UserBaseExtMapper userBaseExtMapper;
    @Autowired
    private ScoreBillMapper scoreBillMapper;
    @Autowired
    private ScoreAccountMapper scoreAccountMapper;
    @Autowired
    private FundAccountMapper fundAccountMapper;
    @Autowired
    private TransactionFundBillMapper transactionFundBillMapper;
    @Autowired
    private AcmTransactionParams acmTransactionParams;

    final static String MER_ROLE_ID = "1";
    final static String ALLY_ROLE_ID = "2";
    @Override
    public boolean migrateFundBillPage(QueryTablePageDTO dto) {
        String url = acmTransactionParams.getKaolakuaishouHost();
        String uri = "/query/pay/account/detail/limit";
        url = url + uri;

        JSONArray jsonArray = commonMigrateService.pullDataFromKS(url, dto.toJSON());
        if (jsonArray.size() == 0) {
            return false;
        }
        //parse（字符串转对象）的时候 设置下划线转驼峰
        ParserConfig.getGlobalInstance().propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        //这个是每次要换的
        List<FundBillDTO> fundBillDTOS = jsonArray.toJavaList(FundBillDTO.class);
        saveFundBill(fundBillDTOS);

        return true;
    }

    @Override
    public boolean migrateFundBillOrder(QueryTableDateDTO dto) {

        String uri = "/query/pay/account/detail/order";
        String url = acmTransactionParams.getKaolakuaishouHost() + uri;


        JSONArray jsonArray = commonMigrateService.pullDataFromKS(url, dto.toJSON());
        if (jsonArray.size() == 0) {
            return false;
        }
        //parse（字符串转对象）的时候 设置下划线转驼峰
        ParserConfig.getGlobalInstance().propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;

        List<FundBillDTO> fundBillDTOS = jsonArray.toJavaList(FundBillDTO.class);
        saveFundBill(fundBillDTOS);
        return true;
    }


    private void saveFundBill(List<FundBillDTO> fundBillDTOS) {
        List<FundBill> fundBill20s = new ArrayList<>();
        List<ScoreBill> scoreBills = new ArrayList<>();

        for (FundBillDTO fundBillDTO : fundBillDTOS) {
            try {
                LocalDateTime billCreateTime = LocalDateUtils.stringToLocalDateTime(fundBillDTO.getCreateTime());
                LocalDateTime migrateEndTime = LocalDateUtils.stringToLocalDateTime("2020-11-11 00:00:00");
                if (fundBillDTO.getTransactionId().substring(0, 4).equals("LYCS") && billCreateTime.isAfter(migrateEndTime)) {
                    KLog.info("返佣提现11号之后的不迁移:{}",fundBillDTO);
                    continue;
                }

                //快收的积分类型的交易明细 4,5,8
                String userBaseId = getUserBaseId(userBaseExtMapper, fundBillDTO.getUserId(), redis);
                if (fundBillDTO.getType() == 4 || fundBillDTO.getType() == 5 || fundBillDTO.getType() == 8) {
                    if (StringUtils.equals(fundBillDTO.getRoleId(),(MER_ROLE_ID))) {
                        KLog.info("非盟友积分账户明细不迁移");
                        continue;
                    }
                    ScoreBill scoreBill = new ScoreBill();
                    scoreBill.setUserBaseId(userBaseId);
                    try {
                        scoreBill.setScoreAccountId(getScoreAccountId(scoreAccountMapper, userBaseId, ScoreAccountType.getFullCode(ScoreAccountType.ALLY, PlatNoEnums.KLKS.getCode())));
                    }catch (Exception e ){
                        KLog.info("设置积分账户id失败,{}",fundBillDTO.toString(),e);
                    }
                    scoreBill.setOrderId(fundBillDTO.getTransactionId());
                    scoreBill.setAmount(fundBillDTO.getAmount());
                    scoreBill.setType(FundBillType.convertKuaiShouType(fundBillDTO.getType()));
                    LocalDate transDate = LocalDateUtils.stringToLocalDate(fundBillDTO.getTransDate(), DateFormat.DATE_DEFAULT.getPartten());
                    scoreBill.setTransactionMonth(LocalDateUtils.localDateByFormat(transDate, DateFormat.DATE_MONTH.getPartten()));
                    scoreBill.setTransactionDay(LocalDateUtils.localDateByFormat(transDate, DateFormat.DATE_COMPACT.getPartten()));
                    scoreBill.setRemark("账户明细迁移");
                    scoreBill.setChannelId(ChannelIdEnums.no.getCode());
                    scoreBill.setPlatNo(PlatNoEnums.KLKS.getCode());
                    scoreBill.setIsDel(false);
                    scoreBill.setShowFlag(true);
                    scoreBill.setCreateTime(fundBillDTO.getCreateTime() == null ? LocalDateTime.now()
                            : LocalDateUtils.stringToLocalDateTime(fundBillDTO.getCreateTime()));
                    scoreBill.setUpdateTime(fundBillDTO.getUpdateTime() == null ? LocalDateTime.now()
                            : fundBillDTO.getUpdateTime());

                    scoreBills.add(scoreBill);
                }
                FundBill fundBill20 = new FundBill();
                fundBill20.setUserBaseId(userBaseId);
                try {
                    if (StringUtils.equals(fundBillDTO.getRoleId(), MER_ROLE_ID)) {
                        fundBill20.setFundAccountId(getFundAccountId(fundAccountMapper, userBaseId, AccountType.getFullCode(AccountType.MER, PlatNoEnums.KLKS.getCode())));
                    }else if (StringUtils.equals(fundBillDTO.getRoleId(), ALLY_ROLE_ID)){
                        fundBill20.setFundAccountId(getFundAccountId(fundAccountMapper, userBaseId, AccountType.getFullCode(AccountType.ALLY, PlatNoEnums.KLKS.getCode())));
                    }
                } catch (Exception e) {
                    KLog.info("设置账单明细账户id失败,{}",fundBillDTO.toString(),e);
                }

                // orderid ks转lingyun userId的类型
                Short[] arr = {1, 7, 9, 11, 12, 14};
                if (Arrays.binarySearch(arr, fundBillDTO.getType()) >= 0) {
                    try {
                        fundBill20.setOrderId(getUserBaseId(userBaseExtMapper, fundBillDTO.getTransactionId(), redis));
                    } catch (Exception e) {
                        KLog.info("订单号转userBaseId失败,保留原订单号:{}",fundBillDTO.getTransactionId(),e);
                        fundBill20.setOrderId(fundBillDTO.getTransactionId());
                    }
                } else {
                    fundBill20.setOrderId(fundBillDTO.getTransactionId());
                }

                fundBill20.setAmount(fundBillDTO.getAmount());
                fundBill20.setType(FundBillType.convertKuaiShouType(fundBillDTO.getType()));

                LocalDate transDate = LocalDateUtils.stringToLocalDate(fundBillDTO.getTransDate(), DateFormat.DATE_DEFAULT.getPartten());
                fundBill20.setTransactionMonth(LocalDateUtils.localDateByFormat(transDate, DateFormat.DATE_MONTH.getPartten()));
                fundBill20.setTransactionDay(LocalDateUtils.localDateByFormat(transDate, DateFormat.DATE_COMPACT.getPartten()));
                fundBill20.setRemark("账户明细迁移");
                fundBill20.setChannelId(ChannelIdEnums.no.getCode());
                fundBill20.setPlatNo(PlatNoEnums.KLKS.getCode());
                fundBill20.setIsDel(false);
                fundBill20.setShowFlag(true);
                fundBill20.setCreateTime(fundBillDTO.getCreateTime() == null ? LocalDateTime.now()
                        : LocalDateUtils.stringToLocalDateTime(fundBillDTO.getCreateTime()));
                fundBill20.setUpdateTime(fundBillDTO.getUpdateTime() == null ? LocalDateTime.now()
                        : fundBillDTO.getUpdateTime());

                fundBill20s.add(fundBill20);
            } catch (Exception e) {
                KLog.error("迁移账户明细失败,账户:{}", fundBillDTO, e);
                continue;
            }
        }
        if (fundBill20s.size() != 0) {
            int i = transactionFundBillMapper.batchInsert(PlatNoEnums.KLKS.getCode(), fundBill20s);
            KLog.info("[账户明细迁移]批量插入资金明细结束,条数:{}", i);
        }
        if (scoreBills.size() != 0) {
            int i = scoreBillMapper.batchInsert(scoreBills);
            KLog.info("[账户明细迁移]批量插入积分明细结束,条数:{}", i);
        }
    }
}


